package com.cskaoyan.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.cskaoyan.properties.DataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @EnableConfigurationProperties建立配置类和参数类之间的关系
 * 包含了把参数类注册为容器中的组件的功能
 * @author stone
 * @date 2021/11/26 10:57
 */
@EnableConfigurationProperties(DataSourceProperties.class)
@Configuration
public class DataSourceConfiguration {

    DataSourceProperties properties;

    //配置类实例化方式，就变更为了有参构造方法；
    // 形参也是从容器中取出组件（类似于@Bean对应方法的形参）
    public DataSourceConfiguration(DataSourceProperties properties) {
        this.properties = properties;
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        return dataSource;
    }
}
